
import 'dart:async';
import 'package:ali_vod_video/ali_vod_video.dart';
import 'package:ali_vod_video/upload_callback.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'media_library_index_service.dart';

///视频上传工具类
class MediaLibraryVideoUploadService {
  static MediaLibraryVideoUploadService _instance;

  ///通知上传数据变化
  StreamController<List<UploadMediaLibraryItemBean>> uploadServiceStream;
  ///正在上传的视频信息集合
  Map<String,List<UploadMediaLibraryItemBean>> _uploadingInfoMap;
  ///正在上传视频通知流集合
  Map<String, StreamController<UploadMediaLibraryItemBean>> uploadingStreamMap;
  ///上传实例
  Map<String, AliVodVideo> _uploadingInstanceMap;

  MediaLibraryVideoUploadService(){
    uploadServiceStream = StreamController.broadcast();
    _uploadingInfoMap = Map();
    uploadingStreamMap = Map();
    _uploadingInstanceMap = Map();
  }

  static MediaLibraryVideoUploadService getInstance() {
    if (_instance == null) {
      _instance = new MediaLibraryVideoUploadService();
    }
    return _instance;
  }

  List<UploadMediaLibraryItemBean> getAllUploadingInfoList(){
    List<UploadMediaLibraryItemBean> allUploadingInfoList = List();
    _uploadingInfoMap.forEach((key, value) {
      allUploadingInfoList.addAll(value);
    });
    return allUploadingInfoList;
  }


  List<UploadMediaLibraryItemBean> getUploadingInfoList(String hsn){
    return _uploadingInfoMap[hsn];
  }

  //从所有列表中获取某个视频上传的进度
  UploadMediaLibraryItemBean getCurrentUploadingInfoFromAll(String id){
    UploadMediaLibraryItemBean tempInfo = getAllUploadingInfoList()?.where((info) => info?.id == id)?.first;
    return tempInfo;
  }

  //从终端视频上传列表中获取某个视频上传的进度
  UploadMediaLibraryItemBean getCurrentUploadingInfoFromTerminal(String hsn, String id){
    UploadMediaLibraryItemBean tempInfo = _uploadingInfoMap[hsn]?.where((info) => info?.id == id)?.first;
    return tempInfo;
  }

  void cancelUpload(String id, String path){
    _uploadingInstanceMap[id]?.cancelUploadVideo(id, path);
  }

  void cancelAll(String id){
    _uploadingInstanceMap[id]?.cancelUploadVideoAll();
    _uploadingInfoMap?.values?.forEach((uploadingInfoList) {
      uploadingInfoList.forEach((info) {
        info.status=UploadStatus.stop;
        //通知更新进度
        uploadingStreamMap[info?.id].add(info);
      });
    });
    _uploadingInfoMap?.clear();
    uploadingStreamMap?.clear();
    uploadServiceStream.add(null);
  }

  ///上传
  void upload(UploadMediaLibraryItemBean item, String hsns, String startDayStr, String endDayStr,
      String allflg, String title, String content, String waterflg, String logoflg)async{


    item.progress = 0;
    String id=DateTime.now().toString();
    item.id = id;
    //根据门店id获取正在上传的视频信息列表
    List<String> hsnList = hsns.split(",");
    hsnList.forEach((hsn) {
      List<UploadMediaLibraryItemBean> uploadingInfoList = _uploadingInfoMap[hsn];
      if(uploadingInfoList == null){
        uploadingInfoList = List();
      }
      uploadingInfoList.add(item);
      _uploadingInfoMap[hsn] = uploadingInfoList;
      uploadServiceStream.add(uploadingInfoList);
    });


    StreamController<UploadMediaLibraryItemBean> stream = StreamController.broadcast();
    stream.add(item);
    uploadingStreamMap[id] = stream;
    try {
      uploadSingleVideo(
        item.id,
        item.localUrl,
        UploadCallback(
            onProgress: (progress, id, {String msg}){
              print("进度-------：" + progress.toString() + msg??"");
              hsnList.forEach((hsn) {
                UploadMediaLibraryItemBean tempInfo = _uploadingInfoMap[hsn]?.where((info) => info?.id == id)?.first;
                if(tempInfo.status != UploadStatus.stop){
                  tempInfo.status=UploadStatus.onProgress;
                }
                tempInfo.progress = progress;
                //通知更新进度
                uploadingStreamMap[id].add(tempInfo);
              });
            },
            onSuccess: (net, fileSize,coverUrl, videoId, sdVideo, sdStorage)async{
              VideoUploadSuccessBean successBean = new VideoUploadSuccessBean(net, fileSize,coverUrl, videoId, sdVideo, sdStorage);
              item.netUrl = successBean.url;
              item.videoid = successBean.videoid;
              item.folderName = VgMatisseUploadUtils.getVideoPath();
              if (!StringUtils.isEmpty(successBean.fileSize)) {
                item.folderStorage = int.parse(successBean.fileSize);
              }
              item.videoNetCover =
              await VgMatisseUploadUtils.uploadSingleImageForFuture(
                  item.videoLocalCover,
                  isNoCompress: false);
              uploadMediaVideoData(item, hsns, startDayStr, endDayStr,
                  allflg, title, content, waterflg, logoflg);
            },
            onError: (msg){
            },
            onCancel: (String id, String path){

              hsnList.forEach((hsn) {
                //根据hsn获取当前终端正在上传的视频信息列表
                List<UploadMediaLibraryItemBean> uploadingInfoList = _uploadingInfoMap[hsn];
                UploadMediaLibraryItemBean currentItem = uploadingInfoList?.where((info) => info?.id == id)?.first;
                currentItem.status=UploadStatus.stop;
                //通知更新进度
                uploadingStreamMap[id].add(currentItem);


                //更新当前终端正在上传的视频信息列表
                uploadingInfoList?.remove(uploadingInfoList?.where((info) => info?.id == id)?.first);
                _uploadingInfoMap[hsn] = uploadingInfoList;
                //通知此门店上传视频数据的监听stream 进行更新
                uploadServiceStream.add(uploadingInfoList);
              });


              uploadingStreamMap.remove(id);
            }
        ),);

    } catch (e) {
      print("MediaLibraryIndexService上传异常：$e");
    }
  }


  uploadMediaVideoData(UploadMediaLibraryItemBean item, String hsns, String startDayStr, String endDayStr,
      String allflg, String title, String content, String waterflg, String logoflg){
    List<String> hsnList = hsns.split(",");
    //接口
    String url;
    url = MediaLibraryIndexService.UPLOAD_MEDIA_LIBRARY_WITH_TERMINAL_SETTINGS_API;
    Map<String, dynamic> paramsMap = {
      "authId": UserRepository.getInstance().authId ?? "",
      "picname": item.folderName ?? "",
      "picsize": item?.getSize() ?? "",
      "picstorage": item?.getStorage() ?? "",
      "picurl": item?.netUrl ?? "",
      "type": item?.mediaType?.getParamsValue() ?? "",
      "videopic": item?.videoNetCover ?? "",
      "videotime": item?.videoDuration ?? 0,
      "videoid": item?.videoid ?? "",
      "hsns": hsns ?? null,
      "startday": startDayStr ?? null,
      "endday": endDayStr ?? null,
      "allflg": allflg ?? null,
      "title": title ?? null,
      "subtitle": content ?? null,
      "waterflg": waterflg ?? "01",
      "logoflg": logoflg ?? "01",
    };
    print("准备上传测试参数: ${paramsMap}");
    VgHttpUtils.get(url,
        params: paramsMap,
        callback: BaseCallback(onSuccess: (val) {

          hsnList.forEach((hsn) {
            //根据hsn获取当前终端正在上传的视频信息列表
            List<UploadMediaLibraryItemBean> uploadingInfoList = _uploadingInfoMap[hsn];
            //更新当前终端正在上传的视频信息列表
            uploadingInfoList?.remove(uploadingInfoList?.where((info) => info?.id == item?.id)?.first);
            _uploadingInfoMap[hsn] = uploadingInfoList;
            //通知此终端上传视频数据的监听stream 进行更新
            uploadServiceStream.add(uploadingInfoList);

          });

          item.progress = 100;
          //通知更新进度
          uploadingStreamMap[item?.id].add(item);
          uploadingStreamMap.remove(item?.id);

          VgEventBus.global.send(new MediaLibraryRefreshEven());


        }, onError: (msg) {
          hsnList.forEach((hsn) {
            //根据hsn获取当前终端正在上传的视频信息列表
            List<UploadMediaLibraryItemBean> uploadingInfoList = _uploadingInfoMap[hsn];
            //更新当前终端正在上传的视频信息列表
            uploadingInfoList?.remove(uploadingInfoList?.where((info) => info?.id == item?.id)?.first);
            _uploadingInfoMap[hsn] = uploadingInfoList;
            //通知此终端上传视频数据的监听stream 进行更新
            uploadServiceStream.add(uploadingInfoList);

          });
          uploadingStreamMap.remove(item?.id);
          VgToastUtils.toast(AppMain.context, "上传失败:" + msg);
        }));

  }



  void uploadSingleVideo(String id, String path, UploadCallback callback){
    if(StringUtils.isEmpty(path)){
      callback.onError("路径获取失败");
    }
    if(VgStringUtils.isNetUrl(path)){
      callback.onSuccess(path, "","", "", "", "");
    }
    String cateId = ("http://et.lemontry.com/" ==ServerApi.BASE_URL)?"2061":"2165";
    print("VgMatisseUploadUtils:" + cateId);
    String userData = '{"MessageCallback":{"CallbackURL":"'+ServerApi.BASE_URL+'aliyunvod/transcodingCallback","CallbackType":"http"}, "Extend":"00"}';
    AliVodVideo uploadInstance = new AliVodVideo();
    _uploadingInstanceMap[id] = uploadInstance;
    uploadInstance.uploadVideo(id, cateId, ConstantRepository.of().getTemplateGroupId(),
        ConstantRepository.of().getDefinition(), path, userData, UploadCallback(
            onSuccess: (net, fileSize,coverUrl, videoId, sdVideo, sdStorage){
              _uploadingInstanceMap[id] = null;
              _uploadingInstanceMap.remove(id);
              if(net == null || net == ""){
                callback.onError("数据空");
                print("VgMatisseUploadUtils:数据空");
                return;
              }
              print("VgMatisseUploadUtils:net:" + net);
              callback.onSuccess(net, fileSize,coverUrl, videoId, sdVideo, sdStorage);
            },
            onError: (msg){
              _uploadingInstanceMap[id] = null;
              _uploadingInstanceMap.remove(id);
              print("VgMatisseUploadUtils:onError:" + msg);
              callback.onError(msg);
            },
            onProgress: (progress, id, {String msg}){
              callback.onProgress(progress, id, msg:msg);
            },
            onCancel: (String currentId, String path){
              _uploadingInstanceMap[id] = null;
              _uploadingInstanceMap.remove(currentId);
              callback.onCancel(currentId, path);
            }
        ), needProgress: true);
  }

}